//
//  AppleLogin.m
//  OpenSDK
//
//  Created by 涂俊 on 2020/1/15.
//  Copyright © 2020 WYHT. All rights reserved.
//

#import "AppleLogin.h"

#import "OpenSDK_DataKeys.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_HttpUtil.h"
#import <AuthenticationServices/AuthenticationServices.h>

/// Apple User Id Key
static NSString *appleLoginUserIdKey = @"appleLoginUserIdKey";
static NSString *appleGivenNameKey = @"appleGivenNameKey";

@interface AppleLogin () <ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>
@property(nonatomic, assign)BOOL isLogin;
@end

@implementation AppleLogin

- (NSString *)getServerName {
    return @"AppleLogin";
}

- (void)initInfo {
    [OpenSDK_EventManager addObsver:self selector:@selector(application_didFinishLaunchingWithOptions:) name:OPENSDK_EVENT_APPLICATION_DIDFINISHLAUNCHINGWITHOPTIONS object:nil className:@"AppleLogin"];
}
- (NSString *)getBackgroundImage {
    return @"op_login_type_apple_bg";
}

- (NSString *)getDisplayIcon {
    return @"op_login_type_apple";
}

- (NSString *)getDisplayName {
    return @"Apple登录";
}

-(NSString *) getDisplaySdkName {
    return @"苹果账号";
}

- (NSString *)getPlatform {
    return @"AppleLogin";
}

- (NSString *)getPlatformVersion {
    return @"1.0";
}


#pragma mark - OpenSDK调起Apple登录
- (void)startLogin {
    _isLogin = YES;
    [self requestApple];
}

- (void)startAuth {
    _isLogin = NO;
    [self requestApple];
}


- (void)requestApple {
    // 调起苹果登录
    dispatch_async(dispatch_get_main_queue(), ^{
        if (@available(iOS 13.0, *)) {
            // 基于用户的Apple ID授权用户，生成用户授权请求的一种机制
            ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
            // 创建新的AppleID 授权请求
            ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
            // 在用户授权期间请求的联系信息
            appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
            // 由ASAuthorizationAppleIDProvider创建的授权请求 管理授权请求的控制器
            ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
            // 设置授权控制器通知授权请求的成功与失败的代理
            authorizationController.delegate = self;
            // 设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
            authorizationController.presentationContextProvider = self;
            // 在控制器初始化期间启动授权流
            [authorizationController performRequests];
        }else{
            // 处理不支持系统版本
            [[[OpenSDK_iToast makeText:@"抱歉，您目前的系统版本，不可用Apple登录"] setDuration:2000] show];
        }
    });
}

#pragma mark - 系统初始化回调，检测Apple登录状态
-(void) application_didFinishLaunchingWithOptions:(NSNotification*) notification {
    //检测apple登录状态
    if (@available(iOS 13.0, *)) {
        NSString *userIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:appleLoginUserIdKey];
        if (userIdentifier) {
            ASAuthorizationAppleIDProvider *appleIDProvider = [ASAuthorizationAppleIDProvider new];
            [appleIDProvider getCredentialStateForUserID:userIdentifier completion:^(ASAuthorizationAppleIDProviderCredentialState credentialState,
                                                           NSError * _Nullable error)
            {
                switch (credentialState) {
                    case ASAuthorizationAppleIDProviderCredentialAuthorized:
                        // 授权状态有效
                        NSLog(@"用户已经登录。userId=%@", userIdentifier);
                        break;
                    case ASAuthorizationAppleIDProviderCredentialRevoked:
                        // 上次使用苹果账号登录的凭据已被移除，需解除绑定并重新引导用户使用苹果登录；
                        NSLog(@"用户登录已失效，需要重新登录。userId=%@", userIdentifier);
                        [[NSUserDefaults standardUserDefaults] removeObjectForKey:appleLoginUserIdKey];
                        break;
                    case ASAuthorizationAppleIDProviderCredentialNotFound:
                        // 未登录授权，直接弹出登录页面，引导用户登录。
                        NSLog(@"用户未登录。userId=%@", userIdentifier);
                        break;
                    case ASAuthorizationAppleIDProviderCredentialTransferred:
                        break;
                }
            }];
        }
    }
}


#pragma mark - Sign in with Apple展示回调
-(ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)) {
   return [OpenSDK_UIUtil getCurrentWindow];
}

#pragma mark - Sign in with Apple授权成功的回调
-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential * credential = authorization.credential;
        NSString *state = credential.state;
        NSString * userID = credential.user;
        NSPersonNameComponents *fullName = credential.fullName;
        NSString *givenName = fullName.givenName;
        if (givenName != nil) {
            [[NSUserDefaults standardUserDefaults] setValue:givenName forKey:appleGivenNameKey];
        } else {
            NSString *gn = [[NSUserDefaults standardUserDefaults] valueForKey:appleGivenNameKey];
            givenName = gn == nil ? @"云畅游戏" : gn;
        }
        NSString * email = credential.email;
        //refresh token
        NSString * authorizationCode = [[NSString alloc]initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
        // access token
        NSString * identityToken = [[NSString alloc]initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
        NSLog(@"state: %@", state);
        NSLog(@"userID: %@", userID);
        NSLog(@"family name: %@ middname: %@ given name: %@, nikename: %@", fullName.familyName, fullName.middleName, fullName.givenName, fullName.nickname);
        NSLog(@"fullName: %@", fullName);
        NSLog(@"email: %@", email);
        NSLog(@"authorizationCode: %@", authorizationCode);
        NSLog(@"identityToken: %@", identityToken);
        NSLog(@"realUserStatus: %@", @(realUserStatus));
        [[NSUserDefaults standardUserDefaults] setObject:userID forKey:appleLoginUserIdKey];
        if (_isLogin) {
            [OpenSDK_HttpUtil loginWithOtherSDK:@{@"nickName": givenName,
                                                  @"userId": userID,
                                                  @"identityToken": identityToken}
                                       platform:[self getPlatform]
                                platformVersion:[self getPlatformVersion]
                                   httpDelegate:self.loginDelegate];
        } else {
            if (self.loginDelegate) {
                OpenSDK_BaseResData *data = [[OpenSDK_BaseResData alloc] init];
                data.status = @"ok";
                data.content = @{@"nickName": givenName,
                                 @"userId": userID,
                                 @"identityToken": identityToken,
                                 @"oauth_type": [self getPlatform],
                                 @"platform_version": [self getPlatformVersion]}.mutableCopy;
                self.loginDelegate(data);
            }
        }
    }
}

#pragma mark - Sign in with Apple授权失败的回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    
    NSString * errorMsg = nil;
    
    switch (error.code) {
            case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
            case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
            case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
            case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
            case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }
    NSLog(@"Apple登录授权失败：%@", errorMsg);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.loginDelegate) {
            OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
            [resData fail];
            [resData setErrorMsg:errorMsg];
            [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
            self.loginDelegate(resData);
        }
    });
}

@synthesize loginDelegate;

@end
